﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
using AnalisisDeRiesgosConfiguration.Exceptions;

namespace AnalisisDeRiesgosConfiguration.DataAccess
{
    class ScriptExecutor
    {
        DatabaseConnectionString connectionString;

        public ScriptExecutor(DatabaseConnectionString theConnectionString)
        {
            connectionString = theConnectionString;
        }

        public void CreateDataBase()
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString.ConnectionStringMySQL))
                {
                    connection.Open();
                    string sql = File.ReadAllText("./scriptbd.sql");
                    MySqlScript script = new MySqlScript(connection, sql);

                    script.Execute();
                    connection.Close();
                }

            }
            catch (Exception ex)
            {
                throw new DataAccessException(ex.Message);
            }
        }

        public void AssignPermissions(string username)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString.ConnectionStringMySQL))
                {
                    connection.Open();
                    string sql = "GRANT SELECT ON riskanalysis.* TO " + username + "@'localhost';" +
                                  "GRANT DELETE ON riskanalysis.* TO " + username + "@'localhost';" +
                                  "GRANT UPDATE ON riskanalysis.* TO " + username + "@'localhost';" +
                                  "GRANT INSERT ON riskanalysis.* TO " + username + "@'localhost';";
                    MySqlScript script = new MySqlScript(connection, sql);

                    script.Execute();
                    connection.Close();
                }

            }
            catch (Exception ex)
            {
                throw new DataAccessException(ex.Message);
            }
        }
    }
}
